﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Collections;
using System.Text.RegularExpressions;

namespace Heroius.DBTransitor
{
    public partial class FormStringBuilder : Form
    {
        internal FormStringBuilder(string Title, SqlConnectionStringBuilder ConnectionStringBuilder, bool LoadFromCurrent)
        {
            InitializeComponent();
            this.Text = Title;
            RbAutUser.CheckedChanged += RbAutUser_CheckedChanged;
            ChbSrcAtc.CheckedChanged += ChbSrcAtc_CheckedChanged;
            if (LoadFromCurrent)
            {
                CbSrc.Text = ConnectionStringBuilder.DataSource;
                ChbSrcAtc.Checked = !string.IsNullOrEmpty(ConnectionStringBuilder.AttachDBFilename);
                TbCat.Text = ConnectionStringBuilder.InitialCatalog;
                RbAutInt.Checked = ConnectionStringBuilder.IntegratedSecurity;
                if (RbAutUser.Checked)
                {
                    TbUser.Text = ConnectionStringBuilder.UserID;
                    TbPwd.Text = ConnectionStringBuilder.Password;
                }
            }
            _ConnectionStringBuilder = ConnectionStringBuilder;
        }

        SqlConnectionStringBuilder _ConnectionStringBuilder;

        void ChbSrcAtc_CheckedChanged(object sender, EventArgs e)
        {
            BtnAtcBrowse.Enabled = ChbSrcAtc.Checked;
        }

        void RbAutUser_CheckedChanged(object sender, EventArgs e)
        {
            PanelAut.Enabled = RbAutUser.Checked;
        }

        private void BtnSrcBrowse_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("此操作将持续较长时间，是否继续操作？", "确认动作", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                CbSrc.Items.Clear();
                DataTable BrowseResults = SqlDataSourceEnumerator.Instance.GetDataSources();
                foreach (DataRow Row in BrowseResults.Rows)
                {
                    CbSrc.Items.Add(string.Format("{0}\\{1}", Row["ServerName"], Row["InstanceName"]));
                }
                if (CbSrc.Items.Count == 0)
                    CbSrc.Items.Add("(LOCAL)");
            }
        }

        private void BtnAtcBrowse_Click(object sender, EventArgs e)
        {
            DiaOpen.ShowDialog();
        }

        private void DiaOpen_FileOk(object sender, CancelEventArgs e)
        {
            TbCat.Text = DiaOpen.FileName;
        }

        private void BtnTest_Click(object sender, EventArgs e)
        {
            SqlConnectionStringBuilder TestCstr = new SqlConnectionStringBuilder();
            if (ModifyStringWithUI(TestCstr))
            {
                SqlConnection TestConn = new SqlConnection(TestCstr.ConnectionString);
                try
                {
                    TestConn.Open();
                    MessageBox.Show("成功！");
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally { TestConn.Close(); }
            }
        }

        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            if (ModifyStringWithUI(_ConnectionStringBuilder))
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        bool ModifyStringWithUI(SqlConnectionStringBuilder Subject)
        {
            //todo:plenty of regex
            try
            {
                Subject.DataSource = AfterValidation("", CbSrc.Text);
                Subject.InitialCatalog = AfterValidation("", TbCat.Text);
                if (ChbSrcAtc.Checked)
                { Subject.AttachDBFilename = TbAtc.Text; }
                Subject.IntegratedSecurity = RbAutInt.Checked;
                if (RbAutUser.Checked)
                {
                    Subject.UserID = AfterValidation("", TbUser.Text);
                    Subject.Password = AfterValidation("", TbPwd.Text);
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        string AfterValidation(string Validator, string Content)
        {
            Regex RegV = new Regex(Validator);
            if (RegV.IsMatch(Content)) return Content;
            else throw new Exception("参数内容有误：" + Content);
        }
    }
}
